package cn.yfxu.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.yfxu.server.pojo.*;
import cn.yfxu.server.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yfxu
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    private IEmployeeService employeeService;
    private IDepartmentService departmentService;
    private IJoblevelService joblevelService;
    private INationService nationService;
    private IPositionService positionService;
    private IPoliticsStatusService politicsStatusService;

    public EmployeeController(IEmployeeService employeeService, IDepartmentService departmentService, IJoblevelService joblevelService, INationService nationService, IPositionService positionService, IPoliticsStatusService politicsStatusService) {
        this.employeeService = employeeService;
        this.departmentService = departmentService;
        this.joblevelService = joblevelService;
        this.nationService = nationService;
        this.positionService = positionService;
        this.politicsStatusService = politicsStatusService;

    }

    @ApiOperation(value = "分页查询所有员工")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "currentPage", value = "当前页", dataType = "Integer"),
//            @ApiImplicitParam(paramType = "path", name = "size", value = "大小", dataType = "Integer")
//    })
    @RequestMapping(method = RequestMethod.GET, value = "/")
    public PageResult getEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                  @RequestParam(defaultValue = "10") Integer size, Employee employee, LocalDate[] beginDateScope) {

        return employeeService.getEmployeeByPage(currentPage, size, employee, beginDateScope);
    }

    @ApiOperation(value = "获取所有部门")
    @RequestMapping(method = RequestMethod.GET, value = "/deps")
    public List<Department> getAllDepartments() {
        return departmentService.getAllDepartments();
    }

    @ApiOperation(value = "获取工号")
    @RequestMapping(method = RequestMethod.GET, value = "/maxWorkID")
    public Result maxWorkID() {
        return employeeService.maxWorkID();
    }

    @ApiOperation(value = "添加员工")
    @RequestMapping(method = RequestMethod.POST, value = "/")
    public Result addEmp(@RequestBody Employee employee) {
        return employeeService.addEmp(employee);
    }

    @ApiOperation(value = "更新员工")
    @RequestMapping(method = RequestMethod.PUT, value = "/")
    public Result updateEmp(@RequestBody Employee employee) {
        if (employeeService.updateById(employee)) {
            return Result.success("更新成功!");
        }
        return Result.error("更新失败!");
    }

    @ApiOperation(value = "删除员工")
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public Result deleteEmp(@PathVariable Integer id) {
        if (employeeService.removeById(id)) {
            return Result.success("删除成功!");
        }
        return Result.error("删除失败!");
    }

    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsStatus")
    private List<PoliticsStatus> getAllPoliticsStatus() {
        return politicsStatusService.list();
    }

    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevel")
    public List<Joblevel> getAllJobLevel() {
        return joblevelService.list();
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> getAllNation() {
        return nationService.list();
    }

    @ApiOperation(value = "获取所有职位")
    @GetMapping("/position")
    public List<Position> getAllPosition() {
        return positionService.list();
    }

    @ApiOperation(value = "导出员工数据")
    @RequestMapping(method = RequestMethod.GET, value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response) {
        List<Employee> list = employeeService.getEmployee(null);
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public Result importEmployee(@RequestPart("file") MultipartFile file) {
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<Position> positionList = positionService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            list.forEach(employee -> {
                employee.setNationid(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                employee.setPosid(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
                employee.setDepartmentid(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
                employee.setJoblevelid(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                employee.setPoliticid(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
            });
            if (employeeService.saveBatch(list)) {
                return Result.success("导入成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("导入失败!");
    }
}
